package com.chris.libs.base.x.mvpp.manager;

import android.content.Context;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;

import java.util.LinkedList;
import java.util.List;

/**
 * Create by Chris Chan
 * Create on 2023/4/3 8:58
 * Use for:
 * Explain:
 */
public class VLayoutManager {
    public Context context;
    public RecyclerView rv;
    public DelegateAdapter delegateAdapter;
    public List<DelegateAdapter.Adapter> adapterList;

    /**
     * 创建一个管理器
     *
     * @param context
     * @param rv
     * @return
     */
    public static VLayoutManager create(Context context, RecyclerView rv) {
        VLayoutManager vLayoutManager = new VLayoutManager();

        vLayoutManager.context = context;
        vLayoutManager.rv = rv;

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(context);

        rv.setLayoutManager(layoutManager);
        //注意：当hasConsistItemType=true的时候，不论是不是属于同一个子adapter，相同类型的item都能复用。表示它们共享一个类型。 当hasConsistItemType=false的时候，不同子adapter之间的类型不共享
        vLayoutManager.delegateAdapter = new DelegateAdapter(layoutManager, false);
        rv.setAdapter(vLayoutManager.delegateAdapter);
        vLayoutManager.adapterList = new LinkedList<>();

        return vLayoutManager;
    }

    /**
     * 为适配器集合增加适配器
     *
     * @param adapter
     */
    public void addAdapter(DelegateAdapter.Adapter adapter) {
        this.adapterList.add(adapter);
    }

    public void addAdapters(DelegateAdapter.Adapter... adapters) {
        for (DelegateAdapter.Adapter adapter : adapters) {
            addAdapter(adapter);
        }
    }

    public void addAdapter(int index, DelegateAdapter.Adapter adapter) {
        insertAdapter(index, adapter);
    }

    /**
     * 在适配器集合的某个位置插入一个适配器
     *
     * @param index
     * @param adapter
     */
    public void insertAdapter(int index, DelegateAdapter.Adapter adapter) {
        this.adapterList.add(index, adapter);
    }

    public void clear() {
        this.adapterList.clear();
        ready();
    }

    /**
     * 一切准备停当
     */
    public void ready() {
        this.delegateAdapter.setAdapters(this.adapterList);
    }

    /**
     * 数据有更新
     */
    public void update() {
        this.delegateAdapter.notifyDataSetChanged();
    }
}
